package controller;

import gson.Questions;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.google.gson.Gson;

@SuppressWarnings("serial")
public class ShowLinkServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setCharacterEncoding("utf-8");
		String sitemap = request.getParameter("sitemap");
		String reglink = request.getParameter("reglink");
		String type = request.getParameter("type");
		String tag = request.getParameter("tag");
		
		sitemap = Utils.fomatSitemap(sitemap);
		
		String charset="UTF-8";
		//
		Document doc = null;
		
		ArrayList<String> site = Utils.getStachSite();
		
		
		String link="";
		try {
			if(!site.contains(Utils.fomatDmain(sitemap)))
			{
				if(type.equals("html"))
				{
					doc = Jsoup.parse(Utils.GetHtml(sitemap, charset));
					
					String[] arrreglink = reglink.split("\\|");
					if(arrreglink.length>=2)
						link = doc.select(arrreglink[0]).get(Integer.parseInt(arrreglink[1])).attr("href");
					else
						link = doc.select(reglink).get(0).attr("href");
						
				}
				else
				{
					try {
						doc = Jsoup.parse(Utils.GetHtml(sitemap, charset).replaceAll("<link>", "<links>").replaceAll("</link>", "</links>"));
						link = doc.select("item").get(0).select("links").get(0).text();
					} catch (Exception e) {
						link = doc.select("entry link[rel=alternate]").attr("href");
					}
				}
				
				link=Utils.fomatLink(link, sitemap);
			} else {
				String str = Utils.GetHtml("https://api.stackexchange.com/2.1/search/advanced?order=desc&answers=1&sort=activity&tagged="+tag+"&site="+Utils.fomatDmain(sitemap)+"&filter=!T5TVZso8yZqn*VSo%29T&key=vxwi93Z)iv36250wzn6aVA((", "utf-8");
				
				Gson gson = new Gson();
				
				Questions question = gson.fromJson(str, Questions.class);
				link = question.items.get(0).getLink();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		request.setAttribute("str", link);
		
		try {
			request.getRequestDispatcher("/show_link.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
